package com.zonhar.autofeed.controller;

import cn.hutool.core.date.DateUtil;
import com.zonhar.autofeed.common.R;
import com.zonhar.autofeed.common.device.camera.CameraDevice;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("/camera")
public class CameraController {

    /**
     * 捕获图像
     */
    @GetMapping(value = "/takeStill")
    public R takeStill()  {
        String fileName = System.currentTimeMillis() + ".png";
        String url =CameraDevice.takeBufferedStill("/Users/zonhar/Desktop", fileName);
       return R.ok().put("url",url);
    }

    @GetMapping(value = "/getImage",produces = {MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_GIF_VALUE, MediaType.IMAGE_PNG_VALUE})
    public void getImage(String fileName,HttpServletResponse response){
        String path ="/home/pi/Desktop/pic/";
        //String path ="/Users/zonhar/Desktop/";
        File file = new File(path + fileName);
        try {
            FileInputStream fis = new FileInputStream(file);
            long size = file.length();
            byte[] data = new byte[(int) size];
            fis.read(data, 0, (int) size);
            fis.close();
            response.setContentType("image/png");
            OutputStream out = response.getOutputStream();
            out.write(data);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
